<template>
	<view class="add-address">
		<view class="add-address-container">
			<van-field label="姓名" :border="true">
				<view slot="input" class="input">
					<input v-model="addressForm.name" placeholder="请输入姓名" />
				</view>
			</van-field>
			<van-field label="电话" :border="true">
				<view slot="input" class="input">
					<input v-model="addressForm.phone" placeholder="请输入电话" />
				</view>
			</van-field>
			<van-field label="所在地区" :border="true">
				<view slot="input" class="input">
					<picker
						mode="multiSelector"
						:value="tempMultiIndex"
						:range="tempMultiArray"
						@columnchange="onMultiPickerColumnChange"
						@change="onMultiPickerChange">
						<view class="address-info">
							<view class="picker">{{ curProviceName }}, {{ curCityName }}, {{ curRegionName }}</view>
							<view class='iconfont icon-dizhi font-color'></view>
						</view>
					</picker>
				</view>
			</van-field>
			<van-field label="详细地址" :border="true">
				<view slot="input" class="input">
					<input v-model="addressForm.detail" placeholder="请输入详细地址" />
				</view>
			</van-field>
			<van-field :border="true">
				<view slot="input" class="input">
					<van-checkbox :value="addressForm.isDefault" checked-color="#e93323" @change="onSwitchIsDefault">
						设置为默认地址</van-checkbox>
				</view>
			</van-field>

			<button class="submit-btn" @click="onSubmitAddress">{{ submitBtnText }}</button>
		</view>
	</view>
</template>

<script>
	import { mapMutations } from 'vuex'
	import {
		cityList as cityListApi,
		addressEdit as addressEditApi,
		addressDetail as addressDetailApi
	} from '@/api/address'
	import VanField from '@/wxcomponents/vant/field/index'
	import VanCheckbox from '@/wxcomponents/vant/checkbox/index'
	export default {
		components: {
			VanField,
			VanCheckbox
		},
		data() {
			return {
				fromPage: '',
				id: 0,
				addressForm: {
					name: '',
					phone: '',
					detail: '',
					isDefault: false
				},
				cityList: [],
				multiIndex: [0, 0, 0],
				multiArray: [['省'], ['市'], ['区']],
				tempMultiIndex: [],
				tempMultiArray: [],
				cityId: ''
			}
		},
		computed: {
			curProviceName () {
				return this.multiArray[0][this.multiIndex[0]]
			},
			curCityName () {
				return this.multiArray[1][this.multiIndex[1]]
			},
			curRegionName () {
				return this.multiArray[2][this.multiIndex[2]]
			},
			submitBtnText () {
				return this.id ? '立即保存' : '立即添加'
			}
		},
		watch: {
			tempMultiIndex: {
				immediately: true,
				handler (nVal) {
					let province = [],
						city = [],
						region = []
					
					province = this.cityList.map((item) => {
						return item.n
					})
					
					city = this.cityList[this.tempMultiIndex[0]].c.map((item) => {
						return item.n
					})
					
					region = this.cityList[this.tempMultiIndex[0]].c[this.tempMultiIndex[1]].c.map((item) => {
						return item.n
					})

					this.tempMultiArray[0] = province
					this.tempMultiArray[1] = city
					this.tempMultiArray[2] = region
				},
				deep: true
			}
		},
		async created () {
			await this.getCityList()
			this.tempMultiIndex = [0, 0, 0]
		},
		onLoad ({ from, id }) {
			this.fromPage = from || ''
			this.id = id || 0
			if (this.id) {
				uni.setNavigationBarTitle({
				    title: '编辑收货地址'
				})
				this.getAddressDetail()
			}
		},
		methods: {
			...mapMutations({
				SET_CURRENT_ADDRESS: 'SET_CURRENT_ADDRESS'
			}),
			onSwitchIsDefault() {
				this.addressForm.isDefault = !this.addressForm.isDefault
			},
			onMultiPickerColumnChange ({ detail: { column, value } }) {
				let tempMultiIndex = JSON.parse(JSON.stringify(this.tempMultiIndex))
				tempMultiIndex[column] = value
				this.tempMultiIndex = tempMultiIndex
			},
			onMultiPickerChange () {
				this.multiIndex = JSON.parse(JSON.stringify(this.tempMultiIndex))
				this.multiArray = JSON.parse(JSON.stringify(this.tempMultiArray))
				
				this.cityId = this.cityList[this.multiIndex[0]].c[this.multiIndex[1]].v
			},
			onSubmitAddress() {
				const params = {
					address: {
					  province: this.curProviceName,
					  city: this.curCityName,
					  district: this.curRegionName,
					  city_id: this.cityId
					},
					detail: this.addressForm.detail,
					id: this.id,
					is_default: this.addressForm.isDefault,
					phone: this.addressForm.phone,
					real_name: this.addressForm.name
				}
				if (!this._validateAddressForm(params)) {
					return false
				}
				
				this.addressEdit(params)
			},
			async getCityList() {
				const {
					status,
					data,
					msg
				} = await cityListApi()
				if (status === this.API_STATUS_CODE.SUCCESS) {
					this.cityList = data
				} else {
					uni.showToast({
						icon: 'none',
						title: msg,
						duration: 3000
					})
				}
			},
			async addressEdit (params) {
				const {
					status,
					data,
					msg
				} = await addressEditApi(params)
				if (status === this.API_STATUS_CODE.SUCCESS) {
					let tit = this.id === 0 ? '添加' : '更新'
					uni.showToast({
						icon: 'success',
						title: `${tit}成功`
					})
					
					if (this.fromPage === 'order_confirm') {
						const address = {
							province: params.address.province,
							city: params.address.city,
							detail: params.detail,
							district: params.address.district,
							id: params.address.city_id,
							is_default: params.is_default,
							phone: params.phone,
							real_name: params.real_name
						}
						this.SET_CURRENT_ADDRESS(address)
						setTimeout(() => {
							uni.navigateBack({
								delta: 2
							})
						}, 1500)
					} else {
						setTimeout(() => {
							uni.navigateBack()
						}, 1500)
					}
					
				} else {
					uni.showToast({
						icon: 'none',
						title: msg,
						duration: 3000
					})
				}
			},
			async getAddressDetail () {
				const {
					status,
					data,
					msg
				} = await addressDetailApi(this.id)
				if (status === this.API_STATUS_CODE.SUCCESS) {
					this.addressForm = {
					  name: data.real_name,
					  phone: data.phone,
					  detail: data.detail,
					  isDefault: !!data.is_default
					}
					this.cityId = data.city_id
					
					this.multiArray = [[data.province], [data.city], [data.district]]
				} else {
					uni.showToast({
						icon: 'none',
						title: msg,
						duration: 3000
					})
				}
			},
			_validateAddressForm (params) {
				if (!params.real_name) {
					uni.showToast({
						icon: 'none',
						title: '请填写收货人姓名'
					})
					return false
				}
				if (!params.phone) {
					uni.showToast({
						icon: 'none',
						title: '请填写联系电话'
					})
					return false
				} else if (!this.isPhone(params.phone)) {
					uni.showToast({
						icon: 'none',
						title: '请填写正确的联系电话'
					})
					return false
				}
				
				if (!params.address.city_id) {
					uni.showToast({
						icon: 'none',
						title: '请选择所在地区'
					})
					return false
				}
				
				if (!params.detail) {
					uni.showToast({
						icon: 'none',
						title: '请填写详细地址'
					})
					return false
				}
				return true
			}
		}
	}
</script>

<style lang="scss" scoped>
	.add-address {
		&-container {
			.input {
				width: 100%;

				.address-info {
					display: flex;

					.picker {
						flex: 1;
					}
				}
			}

			.submit-btn {
				width: 690rpx;
				height: 86rpx;
				border-radius: 50rpx;
				text-align: center;
				line-height: 86rpx;
				margin: 50rpx auto;
				font-size: 32rpx;
				color: #fff;
				background-color: #e93323;
			}
		}
	}
</style>
